from view.baseview import BaseView
from orm.model import GongShang,GongShangDetail, db
from flask import json
import time

class GongShangView(BaseView):
    def __init__(self):
        pass

    def queryGongShang(self, params):
        """根据条件取得工商注册信息，params：条件参数"""
        result=[]
        where_condition = True
        if params["companyname"]:
            likestr= "%"+params["companyname"] +"%"
            where_condition=(GongShang.companyname ** likestr )
        if params["liaisons"]:
            likestr= "%"+params["liaisons"] +"%"
            where_condition=where_condition &(GongShang.liaisons ** likestr )
        if params["status"]:
            status= params["status"] 
            where_condition=where_condition &(GongShang.status.in_(status))
        if params["createtime"]:
            where_condition=where_condition & ((GongShang.createtime >= params["createtime"][0]) & (GongShang.createtime <= params["createtime"][1]) )
        rows = GongShang.select().where(where_condition).order_by(GongShang.createtime.desc(),GongShang.urgent.desc())
        for row in rows:
            detail = []
            for rec in row.gongshangdetail_set.order_by(+GongShangDetail.id):
                detail.append({"id":rec.id,"title":rec.title,"name":rec.name,
                               "idnumber":rec.idnumber,"phonenumber":rec.phonenumber,
                               "capitalratio":rec.capitalratio,
                               "idcards":json.loads(rec.idcards)})
            data = {
                "id":row.id,
                "companyname":json.loads(row.companyname),
                "businessscope":row.businessscope,
                "registeredcapital":row.registeredcapital,
               "registeredaddress":row.registeredaddress,
               "securities":json.loads(row.securities),
               "leasingagreements":json.loads(row.leasingagreements),
                "createtime":str(row.createtime),
                "ishouseinvoice":row.ishouseinvoice,
                "chaptermoment":json.loads(row.chaptermoment),
              "liaisons":row.liaisons,
              "phonenumber":row.phonenumber,
              "urgent":row.urgent,
              "status":row.status,
              "hander":row.hander_id,
              "handername":row.hander.username,
              "taxtype":row.taxtype,
              "paytype":row.paytype,
              "comtype":row.comtype,             
              "detail":detail,
               }
            result.append(data )
        return super().resultSet(200, "", result)
    @db.atomic()                   
    def addGongShang(self, params):
        """
        添加
        """
        result =[]
        rec = GongShang.create(
            companyname = json.dumps(params["companyname"]),
            businessscope = params["businessscope"],
            registeredcapital = params["registeredcapital"],
            registeredaddress = params["registeredaddress"],
            securities = json.dumps(params["securities"]),
            leasingagreements = json.dumps(params["leasingagreements"]),
            createtime =time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()),
            ishouseinvoice = params["ishouseinvoice"],
            chaptermoment = json.dumps(params["chaptermoment"]),
            liaisons= params["liaisons"],
            phonenumber = params["phonenumber"],
            urgent = params["urgent"],
            status = params["status"],
            hander = params["hander"],
            taxtype = params["taxtype"],
            paytype = params["paytype"],
            comtype = params["comtype"])

        # 添加明细表
        for row in params["detail"]:
            GongShangDetail.create(gongshang_id=rec.id,
                                   title=row["title"],
                                   name=row["name"],
                                   idnumber=row["idnumber"],
                                   phonenumber=row["phonenumber"],
                                   capitalratio=row["capitalratio"],
                                   idcards=json.dumps(row["idcards"],)
                                   )
        return super().resultSet(200, "添加成功", result)
        raise Exception("数据库操作失败")
    
    @db.atomic()                   
    def updateGongShang(self, params):
        """
        更新
        """
        result =[]
        rec = GongShang.get(GongShang.id==params["id"])
        rec.companyname = json.dumps(params["companyname"])
        rec.businessscope = params["businessscope"]
        rec.registeredcapital = params["registeredcapital"]
        rec.registeredaddress = params["registeredaddress"]
        rec.securities = json.dumps(params["securities"])
        rec.leasingagreements = json.dumps(params["leasingagreements"])
        rec.ishouseinvoice = params["ishouseinvoice"]
        rec.chaptermoment = json.dumps(params["chaptermoment"])
        rec.liaisons= params["liaisons"]
        rec.phonenumber = params["phonenumber"]
        rec.urgent = params["urgent"]
        rec.status = params["status"]
        rec.hander = params["hander"]
        rec.taxtype = params["taxtype"]
        rec.paytype = params["paytype"]
        rec.comtype = params["comtype"]
        rec.save()
        # 清空组织结构明细表
        GongShangDetail.delete().where(GongShangDetail.gongshang_id ==params["id"]).execute()
        # 添加明细表
        for row in params["detail"]:
            GongShangDetail.create(gongshang_id=params["id"],
                                   title=row["title"],
                                   name=row["name"],
                                   idnumber=row["idnumber"],
                                   phonenumber=row["phonenumber"],
                                   capitalratio=row["capitalratio"],
                                   idcards=json.dumps(row["idcards"],)
                                   )
        return super().resultSet(200, "更新成功", result)
        raise Exception("数据库操作失败")
    @db.atomic()
    def deleteGongShang(self, ids):
        """
        删除用户
        """
        master = GongShang.delete().where(GongShang.id.in_(ids)).execute()
        detail = GongShangDetail.delete().where(GongShangDetail.gongshang_id.in_(ids)).execute()
        if master and detail:
            return super().resultSet(200, "删除成功", {})
        return super().resultSet(403, "删除失败", {})
        raise Exception("删除失败")